package jp.com.nobnak.commentviewer.live;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import jp.com.nobnak.commentviewer.common.BaseException;
import jp.com.nobnak.commentviewer.common.IAction1;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;

public class ResultHandler implements IAction1<HttpResponse>, IResult {
	private Iterable<IAction1<IResult>> mIterable;
	private ILiveStatus mLiveStatus;
	
	public ResultHandler(Iterable<IAction1<IResult>> iterable) {
		mIterable = iterable;
	}
	
	@Override
	public void call(HttpResponse param1) {
		try {
			HttpEntity responseEntity = param1.getEntity();
			if (responseEntity == null) 
				throw new ResultHandlerException("Response is null"); 
			SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
			PlayerStatusSaxHandler handler = new PlayerStatusSaxHandler();
			parser.parse(responseEntity.getContent(), handler);
			
			final ILiveStatus liveStatus = handler.getResult();
			if (liveStatus.getErrorCode() != null)
				throw new ResultHandlerException(liveStatus.getErrorCode());
			
			for (IAction1<IResult> listener : mIterable)
				listener.call(new IResult() {
					@Override
					public ILiveStatus getLiveStatus() { return liveStatus; }
				});
		} catch (ResultHandlerException e) {
			throw e;
		} catch (Exception e) {
			throw new ResultHandlerException(e);
		}
	}
	@Override
	public ILiveStatus getLiveStatus() {
		return mLiveStatus;
	}
	
	static private class ResultHandlerException extends BaseException {
		private static final long serialVersionUID = 6403446445407641462L;

		public ResultHandlerException() {
			super();
		}
		public ResultHandlerException(String detailMessage, Throwable throwable) {
			super(detailMessage, throwable);
		}
		public ResultHandlerException(String detailMessage) {
			super(detailMessage);
		}
		public ResultHandlerException(Throwable throwable) {
			super(throwable);
		}
	}
}